package com.cskaoyan.connectionpool;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.util.LinkedList;

/**
 * 创建日期: 2022/03/23 09:48
 *
 * @author ciggar
 *
 * 实现自己的数据库连接池
 *
 */
public class MyConnectionPool {

    static int INIT_SIZE = 10;
    static int MIN_SIZE = 5;
    static int ADD_CAPCITY = 10;


    // 存放连接的容器 从尾部取、从头部存 JDBC4Connection
    static LinkedList<Connection> connectionPool;

    static {
        // 一开始存放 10个连接
        addCapCity(INIT_SIZE);

    }


    // 获取连接
    public static Connection getConnection(){

        // 去扩容
        if (connectionPool.size() < MIN_SIZE) {

            addCapCity(ADD_CAPCITY);
        }

        Connection connection = connectionPool.removeLast();

        return connection;

    }


    // 返回连接
    public static void  returnConnection(Connection connection){

        connectionPool.addFirst(connection);

    }

    // 扩容的方法
    public static void addCapCity(int size){

        if (connectionPool == null || connectionPool.size() == 0) {
            // 初始化
            connectionPool = new LinkedList<>();
        }
        for (int i = 0; i < size; i++) {
            Connection connection = JDBCUtils.getConnection();
            connectionPool.addFirst(connection);
        }
    }




}
